<template>
    <scroll 
        class="suggest" 
        :data="result"
        :pullup="pullup"
        :beforeScroll="beforeScroll"
        @scrollToEnd="searchMore"
        @beforeScroll="listScroll"
        ref="suggest"
    >
        <ul class="suggest-list">
            <li @click="selectItem(item)" class="suggest-item" v-for="item in result">
                <div class="icon">
                    <i :class="getIconCls(item)"></i>
                </div>
                <div class="name">
                    <p class="text" v-html="getDisplayName(item)"></p>
                </div>
            </li>
            <loading v-show="hasMore"></loading>
        </ul>
        <div v-show="!hasMore && !result.length" class="no-result-wrapper">
          <no-result title="抱歉，暂无搜索结果"></no-result>
        </div>
    </scroll>
</template>

<script>
import { search } from "api/search";
import { ERR_OK } from "api/config";
import { createSong } from "common/js/song";
import Scroll from "base/scroll/scroll";
import Loading from "base/loading/loading";
import Singer from "common/js/singer"
import NoResult from 'base/no-result/no-result'

import {mapMutations,mapActions} from 'vuex'

const TYPE_SINGER = "singer";
const PERPAGE = 20;

export default {
  props: {
    query: {
      type: String,
      default: ""
    },
    showSinger: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      page: 1,
      result: [],
      pullup: true,

      hasMore: true,
      beforeScroll:true
    };
  },
  methods: {
    search() {
      // 重新搜索的时候需要重置状态
      this.page = 1;
      this.hasMore = true;
      this.$refs.suggest.scrollTo(0, 0);

      this.hasMore = true;
      search(this.query, this.page, this.showSinger, PERPAGE).then(resp => {
        console.log('1111')
        console.log(resp);
        console.log(resp.match(/^callback\((.*)\)$/));
        var res= JSON.parse(resp.match(/^callback\((.*)\)$/)[1]);
      
        console.log(res)

        if (res.code === ERR_OK) {
          console.log(res);
          this.result = this._genResult(res.data);

          this._checkMore(res.data);
        }
      });
    },


    // 选中歌曲或者歌手
    selectItem(item) {
      console.log(item);
      if(item.type===TYPE_SINGER){
        const singer = new Singer({
          id:item.singermid,
          name:item.singername
        })
        console.log(singer);
        this.$router.push({
          path:`/search/${singer.id}`
        })
        this.setSinger(singer)
      }else {
        this.insertSong(item)
      }
      this.$emit('select');
    },
    refresh() {
      this.$refs.suggest.refresh()
    },

    //列表滚动事件
    listScroll (){
      this.$emit('listScroll')
    },

    _checkMore(data) {
      const song = data.song;
      if (
        !song.list.length ||
        song.curnum + song.curpage * PERPAGE >= song.totalnum
      ) {
        this.hasMore = false;
      }
    },
    searchMore() {
      if (!this.hasMore) {
        return;
      }
      this.page++;

      search(this.query, this.page, this.showSinger, PERPAGE).then(resp => {
	    var res = JSON.parse(resp.match(/^callback\((.*)\)$/)[1]);
        if (res.code === ERR_OK) {
          this.result = this.result.concat(this._genResult(res.data));
          this._checkMore(res.data);
        }
      });
    },

    //组装歌曲演唱者字符串
    filterSinger(singer) {
      let ret = [];
      if (!singer) {
        return "";
      }
      singer.forEach(s => {
        ret.push(s.name);
      });
      return ret.join("/");
    },

    // 显示内容不同的渲染
    getDisplayName(item) {
      if (item.type === TYPE_SINGER) {
        return item.singername;
      } else {
        console.log();

        return `${item.name}-${item.singer}`;
      }
    },

    // 绑定不同的字体图标
    getIconCls(item) {
      if (item.type === TYPE_SINGER) {
        return "icon-mine";
      } else {
        return "icon-music";
      }
    },

    //组装返回的数据
    _genResult(data) {
      let ret = [];
      //这里的singerid是表明有歌手的
      if (data.zhida && data.zhida.singerid && this.page === 1) {
        ret.push({ ...data.zhida, ...{ type: TYPE_SINGER } });
      }
      if (data.song) {
        ret = ret.concat(this._normalizeSongs(data.song.list));
      }
      console.log("组装后的数组", ret);

      return ret;
    },

    // 把类型转换成song类
    _normalizeSongs(list) {
      let ret = [];
      list.forEach(musicData => {
        if (musicData.songid && musicData.albumid) {
          ret.push(createSong(musicData));
        }
      });

      return ret;
    },
    
    ...mapMutations({
      setSinger:'SET_SINGER'
    }),
    ...mapActions([
      'insertSong'
    ])
  },
  watch: {
    query() {
      this.search();
    }
  },
  components: {
    Scroll,
    Loading,
    NoResult
  }
};
</script>

<style lang="stylus" rel="stylesheet/stylus">
@import '~common/stylus/variable';
@import '~common/stylus/mixin';

.suggest {
  height: 100%;
  overflow: hidden;

  .suggest-list {
    padding: 0 30px;

    .suggest-item {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
    }

    .icon {
      flex: 0 0 30px;
      width: 30px;

      [class^='icon-'] {
        font-size: 14px;
        color: $color-text-d;
      }
    }

    .name {
      flex: 1;
      font-size: $font-size-medium;
      color: $color-text-d;
      overflow: hidden;

      .text {
        no-wrap();
        text-align: left;
        padding-left: 10px;
      }
    }
  }

  .no-result-wrapper {
    position: absolute;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>
